package com.luobd.bpm.business.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.luobd.bpm.business.roles.service.ICoreUserRoleService;
import com.luobd.bpm.business.user.entity.CoreAccount;
import com.luobd.bpm.business.user.entity.CoreUserInfo;
import com.luobd.bpm.business.user.service.IAuthService;
import com.luobd.bpm.business.user.service.ICoreAccountService;
import com.luobd.bpm.business.user.service.ICoreUserInfoService;
import com.luobd.bpm.common.*;
import com.luobd.bpm.common.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@Primary
public class AuthServiceImpl implements IAuthService {



    private static final String TOKEN_PREFIX = "user::token::";


    private static final String CAPTCHA_PREFIX = "captcha::";

    @Resource
    private JWTUtil jwtUtil;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private ICoreAccountService coreAccountService;


    @Resource
    private ICoreUserInfoService coreUserInfoService;

    @Resource
    private ICoreUserRoleService coreUserRoleService;


    @Override
    public ResponseData<String> auth(String username, String password) {
        QueryWrapper<CoreAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accountName",username);
        List<CoreAccount> list = coreAccountService.list(queryWrapper);
        if(list == null || list.isEmpty()) {
            return ResponseData.error("用户不存在或者密码不正确");
        }
        if(list.size() > 1) {
            return ResponseData.error("数据异常,请联系管理员");
        }
        CoreAccount account = list.get(0);
        if(!account.getPassword().equalsIgnoreCase(password)) {
            return ResponseData.error("用户不存在或者密码不正确");
        }
        CoreUserInfo info = coreUserInfoService.getById(account.getUserInfoId());
        List<Role> roles = coreUserRoleService.getRolesByAccountId(account.getId());


        CurrentUserInfo userInfo = new CurrentUserInfo();
        userInfo.setUsername(username);
        userInfo.setTrueName(info.getTrueName());
        userInfo.setRoles(roles);
        userInfo.setUserInfoId(account.getUserInfoId());
        userInfo.setAccountId(account.getId());
        String token = jwtUtil.createToken(userInfo);
        cacheToken(account.getUserInfoId(),token);
        return ResponseData.success(token);
    }


    @Override
    public ResponseData<Boolean> logout() {
        CurrentUserInfo userInfo = CurrentRequestHolder.get();
        removeCache(userInfo.getUserInfoId());
        return ResponseData.success(Boolean.TRUE);
    }

    @Override
    public String getCacheTokenByUserId(Long userId) {
        String key = TOKEN_PREFIX + userId;
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public ResponseData<Base64Captcha> getCaptchaBase64() {
        Base64Captcha captcha = Base64Captcha.of();
        cacheCaptcha(captcha.getId(),captcha.getCode());
        return ResponseData.success(captcha);
    }


    public boolean checkCaptcha(String id, String captcha) {
        Objects.requireNonNull(id, "id不能为空");
        Objects.requireNonNull(captcha, "captcha不能为空");
        String key = CAPTCHA_PREFIX + id;
        String code = redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(code)){
            redisTemplate.delete(key);
            return captcha.equals(code);
        }
        return false;
    }


    private void cacheToken(Long userId,String token) {
        String key = TOKEN_PREFIX + userId;
        redisTemplate.opsForValue().set(key, token);
    }


    private void removeCache(Long userId) {
        String key = TOKEN_PREFIX + userId;
        redisTemplate.delete(key);
    }




    private void cacheCaptcha(String id,String code) {
        String key = CAPTCHA_PREFIX + id;
        // 验证码存在60S
        redisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);
    }


}
